using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Logging.TraceSource;
using Newtonsoft.Json;
using QntPlatform;
using QntPlatform.BinanceApi;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace QntSvc.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //  var rec= JsonConvert.DeserializeObject<Record[]>("[{\"Time\":1600185600000,\"Open\":10800.007,\"High\":11041,\"Low\":10682,\"Close\":11020,\"Volume\":4951.1,\"OpenInterest\":0},{\"Time\":1600272000000,\"Open\":11020,\"High\":11104.977,\"Low\":10765.936,\"Close\":10862,\"Volume\":3751.55,\"OpenInterest\":0},{\"Time\":1600358400000,\"Open\":10863,\"High\":11064,\"Low\":10826,\"Close\":10923.126,\"Volume\":1650.17,\"OpenInterest\":0},{\"Time\":1600444800000,\"Open\":10923,\"High\":11185,\"Low\":10825,\"Close\":11111.537,\"Volume\":2707.32,\"OpenInterest\":0},{\"Time\":1600531200000,\"Open\":11111.537,\"High\":11138,\"Low\":10812,\"Close\":10856,\"Volume\":1979.27,\"OpenInterest\":0},{\"Time\":1600617600000,\"Open\":10858,\"High\":11000,\"Low\":10321,\"Close\":10444,\"Volume\":5563.69,\"OpenInterest\":0},{\"Time\":1600704000000,\"Open\":10439,\"High\":10549,\"Low\":10375,\"Close\":10475,\"Volume\":2534.05,\"OpenInterest\":0},{\"Time\":1600790400000,\"Open\":10473.309,\"High\":10597,\"Low\":10406,\"Close\":10484,\"Volume\":2183.72,\"OpenInterest\":0},{\"Time\":1600876800000,\"Open\":10484.262,\"High\":10591,\"Low\":10152,\"Close\":10571.707,\"Volume\":3264.65,\"OpenInterest\":0},{\"Time\":1600963200000,\"Open\":10571.985,\"High\":10842,\"Low\":10571,\"Close\":10675.97,\"Volume\":3498.14,\"OpenInterest\":0},{\"Time\":1601049600000,\"Open\":10675.97,\"High\":10841,\"Low\":10649.019,\"Close\":10741.86,\"Volume\":1295.23,\"OpenInterest\":0},{\"Time\":1601136000000,\"Open\":10741.113,\"High\":10824,\"Low\":10594,\"Close\":10778,\"Volume\":1737.19,\"OpenInterest\":0},{\"Time\":1601222400000,\"Open\":10779,\"High\":10986,\"Low\":10727.238,\"Close\":10923.234,\"Volume\":2475.72,\"OpenInterest\":0},{\"Time\":1601308800000,\"Open\":10924,\"High\":10934.897,\"Low\":10656.206,\"Close\":10738,\"Volume\":2788.54,\"OpenInterest\":0},{\"Time\":1601395200000,\"Open\":10738.971,\"High\":10889,\"Low\":10654,\"Close\":10797.352,\"Volume\":1495.76,\"OpenInterest\":0},{\"Time\":1601481600000,\"Open\":10797.998,\"High\":10797.998,\"Low\":10797.998,\"Close\":10797.998,\"Volume\":0,\"OpenInterest\":0}]");
            var mdl = new Module();
            mdl.Run();
            CreateHostBuilder(args).Build().Run();

        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
         Host.CreateDefaultBuilder(args)
         .ConfigureLogging((hostBuilder) =>
         {
             FileLogTracer.AddCfg(hostBuilder);
         })
             .ConfigureWebHostDefaults(webBuilder =>
             {
                 webBuilder.UseStartup<Startup>();
             });
    }
    public class FileLogTracer : DelimitedListTraceListener
    {
       static LogLevel DefaultLevel = LogLevel.Information;
       static  string DefaultFilePath = "trace.log";
        static string DefaultSwitchValue = ((int)SourceLevels.Information).ToString();
        public static void AddCfg(ILoggingBuilder builder, string fileName = null, string switchValue = null)
        {
            builder = builder ?? throw new ArgumentNullException(nameof(builder));
            
            if (string.IsNullOrWhiteSpace(switchValue) || string.IsNullOrWhiteSpace(fileName))
                //获取不到，此处设为post不让其执行
                builder.Services.PostConfigure<ILoggerProviderConfiguration<TraceSourceLoggerProvider>>(p =>
                {
                    if (string.IsNullOrWhiteSpace(switchValue))
                    {
                        var lvs = p.Configuration.GetSection("LogLevel").Get<Dictionary<string, LogLevel>>();
                        var levels = LogLevelToSourceLv(lvs.GetValueOrDefault("Default", DefaultLevel), SourceLevels.Information);
                        switchValue = ((int)levels).ToString();
                    }
                    if (string.IsNullOrWhiteSpace(fileName))
                    {
                        fileName = p.Configuration.GetValue<string>("FilePath") ?? DefaultFilePath;
                    }
                });
            
            FileLogTracer log = new FileLogTracer(fileName ?? DefaultFilePath);
            log.Delimiter = ",";
            builder.AddTraceSource(new SourceSwitch("FileLogTracerSwitch_" + switchValue?? DefaultSwitchValue, switchValue?? DefaultSwitchValue), log);
            Trace.AutoFlush = true;
        }

        private static SourceLevels LogLevelToSourceLv(LogLevel logLv, SourceLevels levels)
        {
            switch (logLv)
            {
                case LogLevel.Trace:
                    levels = SourceLevels.All;
                    break;
                case LogLevel.Debug:
                    levels = SourceLevels.Verbose;
                    break;
                case LogLevel.Information:
                    levels = SourceLevels.Information;
                    break;
                case LogLevel.Warning:
                    levels = SourceLevels.Warning;
                    break;
                case LogLevel.Error:
                    levels = SourceLevels.Error;
                    break;
                case LogLevel.Critical:
                    levels = SourceLevels.Critical;
                    break;
                case LogLevel.None:
                    levels = SourceLevels.Off;
                    break;
            }

            return levels;
        }

        public FileLogTracer(string fileName) : base(fileName)
        {
        }

        public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
        {
            Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")+",");
            base.TraceEvent(eventCache, source, eventType, id, message);
        }
    }
    public class TimedExecutService : BackgroundService
    {
        public ILogger<TimedExecutService> _logger;
        public TimedExecutService(ILogger<TimedExecutService> logger)
        {
            this._logger = logger;
        }
        protected override async Task ExecuteAsync(System.Threading.CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation(DateTime.Now.ToString() + "�����Զ����϶�ʱ����");

                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(5000, stoppingToken); //����������ִ��һ��
                    _logger.LogInformation(DateTime.Now.ToString() + " ִ���Զ���������");

                }
                _logger.LogInformation(DateTime.Now.ToString() + "�Զ���������ֹͣ��");
            }
            catch (Exception ex)
            {
                if (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation(DateTime.Now.ToString() + "�Զ����������쳣��" + ex.Message + ex.StackTrace);
                }
                else
                {
                    _logger.LogInformation(DateTime.Now.ToString() + "�Զ����������쳣ֹͣ��");
                }
            }

        }

    }
}
